<template>
  <div class="app-container">


    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="归属部门" prop="deptId">
        <treeselect v-model="queryParams.deptId" :options="deptOptions" :disable-branch-nodes="false" :show-count="true"
                    size="small"
                    :default-expand-level="1"
                    style="width: 240px"
                    placeholder="请选择归属部门"/>
      </el-form-item>
      <el-form-item label="员工姓名" prop="userId" >
        <el-select v-model="queryParams.userId" placeholder="请输入用户名" clearable filterable remote :remote-method="queryUserByName"  :loading="loading">
          <el-option v-for="item in userOptions" :key="item.id" :label="item.label" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="月份" prop="month" >
        <MonthPicker @change="chageDate" lang="zh" :default-month="queryParams.month"></MonthPicker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button icon="el-icon-refresh" @click="aiScheduleAssign">智能排班</el-button>
      </el-form-item>
    </el-form>



    <!-- 数据列表 -->
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-table @cell-mouse-enter="cellEnter" @cell-mouse-leave="cellLeave"
                @mousedown.native="handleMouseDown"
                @mouseup.native="handleMouseUp"
                @cell-click="cellClick"

                border :height=400 ref="multipleTable" v-loading="loading" :data="monthscheduleList">
        <el-table-column fixed=left align="center" show-tooltip-when-overflow label="用户名" prop="nickName" />
        <el-table-column align="center" v-for="(item) in days" :label="item + '号'" :prop="'scheduleDefineName'+item" :column-key="'dayOfMonth'+item" :id="'cell_'+item" />


        <el-table-column fixed=right label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">

            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['schedule:month-schedule:delete']">清空</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
    </el-form>

    <!-- 对话框(班次) -->
    <el-dialog title="请选择要设置的班次" :visible.sync="open" id="scheduleDefineDialog" width="500px" append-to-body>
      <div style="padding-bottom: 10px;">
        <el-col :span="1.5">
          <el-button :type="item.buttonType" v-for="item in schedefineList"
                     plain icon="el-icon"
                     size="mini" @click="saveScheduleDefine(item.id)">{{item.shiftName}}
          </el-button>
        </el-col>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  addMonthschedule,
  aiMonthschedule,
  delMonthschedule,
  exportMonthschedule,
  listMonthschedule,
  updateMonthschedule
} from "@/api/business/monthschedule";

import {renderHoliday} from "@/api/business/holiday";

import {getCountDays} from "@/api/common/commonquery";
import {treeselect} from "@/api/selfcom/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import {listSchedefineOfDeptId} from "@/api/business/schedefine";
import {getMonthOrDefultThisMonth} from "@/utils";
import {MonthPicker} from '@/views/components/wowmonthpicker/src/index'
import {listUserLikeName} from "@/api/selfcom/user";
import {listSchedulerule} from "@/api/business/schedulerule";


export default {
  name: "Monthschedule",
  components: { Treeselect, MonthPicker },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,

      properPrefix : "dayOfMonth",
      properNamePrefix : "scheduleDefineName",

      days: 0,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 月排班表格数据
      monthscheduleList: [],
      scheduleruleList: [],
      // 班次
      schedefineList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: [],
      userOptions: [],
      // 是否显示弹出层
      open: false,
      // 字典
      idOptions: [],
      // 用户ID字典
      userIdOptions: [],
      // 月份字典
      monthOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,
        yearMonth: new Date(),
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          {required: true, message: "用户ID不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.queryParams.month = getMonthOrDefultThisMonth();
    this.days = getCountDays(this.queryParams.month);
    this.getTreeselect();
    this.getSchedefineList();
    this.getList();
    this.getScheduleRules();
  },
  methods: {
    /** 查询月排班列表 */
    getList() {
      this.loading = true;
      this.days = getCountDays(this.queryParams.month);
      listMonthschedule(this.queryParams).then(response => {
        this.monthscheduleList = response.rows;
        this.total = response.total;
        this.loading = false;
        if(this.monthscheduleList.length > 0) {
          this.initScheduleDefineName(this.monthscheduleList);
        }

      });
      renderHoliday(this);
    },

    getScheduleRules() {
      this.loading = true;
      listSchedulerule(this.queryParams).then(response => {
        this.scheduleruleList = response.rows;
      });
    },

    initScheduleDefineName(list) {
      const properPrefix = this.properPrefix;
      const properNamePrefix = this.properNamePrefix;
      for(const item of list) {
        for(let i = 1; i <= 31; i++) {
          const proper = properPrefix + i;
          const properValue = item[proper]; // properValue 是后台存储的班次定义的 id
          if(!! properValue) {
            const name = this.findScheDefineNameById(properValue);
            // console.log("properValue =>" + name)
            item[properNamePrefix + i] = name;
          }
        }
        //console.log("item =>" + JSON.stringify(item))
      }
    },

    findScheDefineNameById(id) {
      //console.log("ud" + id);

      for(let item of this.schedefineList) {
        if(id === item.id) {
          return item.shiftName
        }
      }
      return "未知班次";
    },

    getSchedefineList: function () {
      // this.schedefineList = [{"id": 1, "shiftName": "早班", "buttonType":"warning"}, {"id": 2, "shiftName": "中班", "buttonType":"success"}, {"id": 3, "shiftName": "晚班", "buttonType":"info"}];
      let buttonTypes = ["warning", "success", "info"];
      listSchedefineOfDeptId(this.queryParams).then(response => {
        this.schedefineList = response.rows;
        for (let i = 0; i < this.schedefineList.length; i++) {
          let schedefine = this.schedefineList[i];
          let index = i % buttonTypes.length;
          schedefine["buttonType"] = buttonTypes[index];
        }

      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        userId: undefined,
        month: undefined,
        dayOfMonth1: undefined,
        dayOfMonth2: undefined,
        dayOfMonth3: undefined,
        dayOfMonth4: undefined,
        dayOfMonth5: undefined,
        dayOfMonth6: undefined,
        dayOfMonth7: undefined,
        dayOfMonth8: undefined,
        dayOfMonth9: undefined,
        dayOfMonth10: undefined,
        dayOfMonth11: undefined,
        dayOfMonth12: undefined,
        dayOfMonth13: undefined,
        dayOfMonth14: undefined,
        dayOfMonth15: undefined,
        dayOfMonth16: undefined,
        dayOfMonth17: undefined,
        dayOfMonth18: undefined,
        dayOfMonth19: undefined,
        dayOfMonth20: undefined,
        dayOfMonth21: undefined,
        dayOfMonth22: undefined,
        dayOfMonth23: undefined,
        dayOfMonth24: undefined,
        dayOfMonth25: undefined,
        dayOfMonth26: undefined,
        dayOfMonth27: undefined,
        dayOfMonth28: undefined,
        dayOfMonth29: undefined,
        dayOfMonth30: undefined,
        dayOfMonth31: undefined,
        deleted: undefined,
        creator: undefined,
        updater: undefined,
        createTime: undefined,
        updateTime: undefined,
        tenantId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加月排班";
    },

    /** 当前选中的班次, 选中后提交表单 */
    saveScheduleDefine(scheduleDefineId) {
      let $form = this.form;
      $form.month = this.queryParams.month; // 往 form 中写 userId
      $form.id = this.aimId; // 往 form 中写 userId
      $form.userId = this.aimUserId; // 往 form 中写 userId
      if(!! this.aimFieldNames) {
        this.aimFieldNames.forEach(function (fieldName){
          console.log("fieldName  " + fieldName)
          $form[fieldName] = scheduleDefineId
        })
      }
      // console.log("this.form  " + JSON.stringify($form) )

      this.submitForm();
      this.open = false;
      this.reset();
    },
    /** 点击格子选中 user 或者记录 id */
    cellClick(row, column, cell, event) {
      // console.log("row " + JSON.stringify(row))
      this.aimId = row.id; // 往 form 中写 userId
      this.aimUserId = row.userId; // 往 form 中写 userId
      this.aimFieldNames = [column.columnKey]; //


      // 对话框定位
      this.open = true;
      const dialog = document.querySelector("#scheduleDefineDialog");
      dialog.style.marginTop = (event.y - 200) + "px";

    },
    handleMouseDown(event) {
      // console.log("handleMouseDown...")
      this.flagmousedown = true;
    },
    handleMouseUp(event) {
      // console.log("handleMouseUp...")
      this.flagmousedown = false;
    },
    /** 鼠标经过 */
    cellEnter(row, column, cell, event) {
      // console.log("  event.target.cellIndex  ", event.target.cellIndex)
      if(event.target.cellIndex == 0) {
        this.showRules(event, row.userId);
      }
      this.defaultCellBackground = cell.style.backgroundColor;
      cell.style.backgroundColor = "#44A3BB";
    },
    /** 鼠标离开 */
    cellLeave(row, column, cell, event) {
      cell.style.backgroundColor = this.defaultCellBackground;
    },
    /** 取消排班 */
    clearScheduleClick() {
      this.reset();
      // 格子的属性值
      // 行 id
      clearSchedule(this.form).then(response => {
        this.open = false;
        this.$modal.msgSuccess("取消成功");
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.form.yearMonth = this.queryParams.yearMonth; // 往 form 中写
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateMonthschedule(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addMonthschedule(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },

    aiScheduleAssign() {
      let data = {
        deptId: this.queryParams.deptId,
        userIds: null,
        yearMonth: this.queryParams.yearMonth
      };

      aiMonthschedule(data).then(response => {
        if (response.code === 200) {
          this.msgSuccess("智能排班结束");
          this.open = false;
          this.getList();
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除月排班编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delMonthschedule(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function () {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有月排班数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportMonthschedule(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(function () {
      });
    },

    showRules(event, userId) {
      let zIndex =  10;
      let transferdItems = this.scheduleruleList.map(option => {
        let optLable = "";
        let childrenOpts = [];
        if(userId == option.userId) {
          optLable = "[ " + option.comment + " ]";
          childrenOpts.push({
            label: "删除",
            onClick: () => {
              this.$alert("敬请期待");
            }});
        } else {
          optLable = option.comment;
          childrenOpts.push({
            label: "添加",
            onClick: () => {
              this.$alert("敬请期待");
            }});
        }
        let item = {
          label: optLable,
          children: childrenOpts,
          onClick: () => {
            console.log("xxxxx");
          }
        }
        return item;
      });

      this.$contextmenu({
        items: transferdItems,
        event, // 鼠标事件信息
        customClass: "custom-class", // 自定义菜单 class
        zIndex: zIndex, // 菜单样式 z-index
        minWidth: 230 // 主菜单最小宽度
      });


    },

    chageDate(date) {
      this.queryParams.yearMonth = date.year + '-' + date.monthIndex;
      this.queryParams.month = date.monthIndex;
    },
    /** 查询人 */
    queryUserByName(userName) {
      listUserLikeName(userName).then(response => {
        this.userOptions = response.rows;
      });
    }

  }
};
</script>
<style>

</style>
